package com.mylib.libcore.utils;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.PointF;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.CycleInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.mylib.libcore.R;
import com.mylib.libcore.eventbus.ChangeMessage;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.List;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;

/**
 * activity管理工具
 */
public class ActivityUtil {

    // 采用弱引用持有 Activity ，避免造成 内存泄露
    private WeakReference<Activity> sCurrentActivityWeakRef;

    private List<Activity> activityList = new LinkedList<Activity>();
    private static ActivityUtil instance;

    private ActivityUtil() {

    }

    /**
     * 单例模式中获取唯一的AbActivityManager实例.
     *
     * @return
     */
    public static ActivityUtil getInstance() {
        if (null == instance) {
            instance = new ActivityUtil();
        }
        return instance;
    }


    public void setCurrentActivity(Activity activity) {
        sCurrentActivityWeakRef = new WeakReference<>(activity);
    }

    public Activity getCurrentActivity() {
        Activity currentActivity = null;
        if (sCurrentActivityWeakRef != null) {
            currentActivity = sCurrentActivityWeakRef.get();
        }
        return currentActivity;
    }

    /**
     * 添加Activity到容器中.
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        synchronized (activityList) {
            activityList.add(activity);
        }
    }

    /**
     * 移除Activity从容器中.
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        synchronized (activityList) {
            activityList.remove(activity);
        }
    }

    /**
     * 遍历所有Activity并finish.
     */
    public void clearAllActivity() {
        synchronized (activityList) {
            for (int i = 0; i < activityList.size(); i++) {
                Activity activity = activityList.get(i);
                activityList.remove(activity);
                i--;
                if (activity != null) {
                    activity.finish();
                }
            }
        }
    }

    /**
     * 结束指定Activity
     *
     * @param clazz
     */
    public void finishActivity(Class clazz) {
        synchronized (activityList) {
            for (int i = 0; i < activityList.size(); i++) {
                Activity activity = activityList.get(i);
                if(clazz.isInstance(activity)) {
                    activityList.remove(activity);
                    i--;
                    if (activity != null) {
                        activity.finish();
                    }
                }

            }
        }
    }


    public void backToHome(){
        synchronized (activityList) {
            for (int i = 0; i < activityList.size(); i++) {
              if(i!=0){
                  Activity activity = activityList.get(i);
                  activityList.remove(activity);
                  i--;
                  if (activity != null) {
                      activity.finish();
                  }
              }
            }
        }
    }
    /**
     * 结束指定Activity
     *
     */
    public boolean isContainActivity(Class clazz) {
        synchronized (activityList) {
            for (int i = 0; i < activityList.size(); i++) {
                Activity activity = activityList.get(i);
                if(clazz.isInstance(activity)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * finish掉除activity外的所有Activity
     */
    public void clearAllActivityWithout(Class<?> cls) {
        synchronized (activityList) {
            for (int i = 0; i < activityList.size(); i++) {
                Activity activity1 = activityList.get(i);
                if(!(activity1.getClass().equals(cls))) {
                    activityList.remove(activity1);
                    i--;
                    if (activity1 != null) {
                        activity1.finish();
                    }
                }
            }
        }
    }

    /**
     * 跳转指定activity
     * gotoType 跳转类型
     * aRouterUrl 跳路由地址
     * bundle 传递数据
     */
    public void goToActivity(Context activity, String gotoType,String linkUrl){
        Bundle bundle = new Bundle();
        if(UIUtils.isEmpty(gotoType)){
            return;
        }
        if(gotoType.equals("1")){//外部链接
            try {
                if(UIUtils.isEmpty(linkUrl)){
                    linkUrl="sk.baidu.com";
                }
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(linkUrl);
                intent.setData(content_url);
                startActivity(intent);
            } catch (Exception e) {
                ToastUtil.show("浏览器开启失败");
                e.printStackTrace();
            }
        }

    }
//    /**
//     * 跳转内部web或者外部web
//     */
//    public void goToActivity(Activity activity, String aRouterUrl, Bundle bundle){
//        ARouter.getInstance().build(aRouterUrl).with(bundle).navigation(activity);
//    }
    public void toFullWindows(Activity activity){
        int systemUiVisibility = activity.getWindow().getDecorView().getSystemUiVisibility();
        int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        systemUiVisibility |= flags;
        activity.getWindow().getDecorView().setSystemUiVisibility(systemUiVisibility);
        activity.getWindow().getDecorView().setFocusable(true);
    }
    public void changeRLSysViewTop(Activity activity,View view,boolean isShowView){
        if(!UIUtils.isEmpty(view)){
            RelativeLayout.LayoutParams linearParams =(RelativeLayout.LayoutParams)view.getLayoutParams();
            linearParams.height = ScreenUtils.getStatusHeight(activity);
            view.setLayoutParams(linearParams);
            if(isShowView){
                view.setVisibility(View.VISIBLE);
            }else {
                view.setVisibility(View.GONE);
            }
        }
    }

    public void showStatusView(Activity activity,View view,boolean isShowView){
        if(!UIUtils.isEmpty(view)){
            ViewGroup.LayoutParams linearParams =(ViewGroup.LayoutParams)view.getLayoutParams();
            linearParams.height = ScreenUtils.getStatusHeight(activity);
            view.setLayoutParams(linearParams);
            if(isShowView){
                view.setVisibility(View.VISIBLE);
            }else {
                view.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 设置textview 垂直渐变
     * @param text
     */
    public void setTextViewStyle(TextView text, String colorStart, String colorEnd){
        LinearGradient mLinearGradient =new LinearGradient(0, 0, 0, text.getPaint().getTextSize(), Color.parseColor(colorStart), Color.parseColor(colorEnd), Shader.TileMode.CLAMP);
        text.getPaint().setShader(mLinearGradient);
        text.invalidate();
    }

    /**
     * 设置imageview 左右抖动
     * @param imageView
     */
    public void setImageViewLeftRightAnim(ImageView imageView){
        TranslateAnimation anim = new TranslateAnimation(imageView.getWidth(),
                imageView.getWidth() + 8, imageView.getHeight(), imageView.getHeight());
        anim.setInterpolator(new CycleInterpolator(2f));  //循环次数
        //CycleInterpolator：动画从开始到结束，变化率是循环给定次数的正弦曲线。
        anim.setDuration(2000);//一个周期动画时长
        anim.setRepeatMode(Animation.RESTART );//结束后重新播放
        anim.setRepeatCount(Animation.INFINITE );//一直播放
        imageView.startAnimation(anim);
    }

    /**
     * 设置imageview 上下抖动
     * @param imageView
     */
    public void setImageViewTopBottomAnim(ImageView imageView){
        TranslateAnimation anim = new TranslateAnimation(imageView.getWidth(), imageView.getWidth()+5, imageView.getHeight(), imageView.getHeight()+5);
        anim.setInterpolator(new CycleInterpolator(3f)); //循环次数
        anim.setDuration(2000);//一个周期动画时长
        anim.setRepeatMode(Animation.RESTART );//结束后重新播放
        anim.setRepeatCount(Animation.INFINITE );//一直播放
        imageView.startAnimation(anim);
    }

    /**
     * 动画设置imageview 上下抖动
     * @param imageView
     */
    public void setCoinViewUpDownAnim(View imageView){
        try {
            imageView.clearAnimation();
            TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 5);
            anim.setInterpolator(new CycleInterpolator(3f)); //循环次数
            anim.setDuration(5000);//一个周期动画时长
            anim.setRepeatMode(Animation.RESTART );//结束后重新播放
            anim.setRepeatCount(Animation.INFINITE );//一直播放
            imageView.startAnimation(anim);
        }catch (Exception e){}
    }

    /**
     * 设置imageview 旋转
     * @param imageView
     */
    public void setImageViewRotateAnim(ImageView imageView, float fromDegrees,float toDegrees ) {
        if (imageView != null) {
            RotateAnimation rotateAnimation = new RotateAnimation(fromDegrees, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            rotateAnimation.setDuration(1000);
            rotateAnimation.setRepeatMode(Animation.REVERSE);//结束后倒序播放
            rotateAnimation.setRepeatCount(Animation.INFINITE);//一直播放
            //启动动画
            imageView.startAnimation(rotateAnimation);
        }

    }

    /**
     * 设置imageview 缩放
     * @param imageView
     */
    public void setImageViewScaleAnim(ImageView imageView){

        //定义缩放动画，从中心坐标开始，缩放1.5倍大小
        ScaleAnimation scaleAnimation = new ScaleAnimation(0.8f, 1.2f, 0.8f, 1.2f, Animation.RELATIVE_TO_SELF, 0.4f, Animation.RELATIVE_TO_SELF, 0.4f);
        scaleAnimation.setDuration(2000);
        scaleAnimation.setRepeatMode(Animation.REVERSE );//结束后重新播放
        scaleAnimation.setRepeatCount(Animation.INFINITE );//一直播放
        //启动动画
        imageView.startAnimation(scaleAnimation);
    }

    /**
     * 设置imageview j渐变动画
     * @param imageView
     */
    public void setImageViewAlphaAnim(ImageView imageView){

//        ScaleAnimation scaleAnimation = new ScaleAnimation(0.8f, 1.2f, 0.8f, 1.2f, Animation.RELATIVE_TO_SELF, 0.4f, Animation.RELATIVE_TO_SELF, 0.4f);
//        scaleAnimation.setDuration(2000);
//        scaleAnimation.setRepeatMode(Animation.REVERSE );//结束后重新播放
//        scaleAnimation.setRepeatCount(Animation.INFINITE );//一直播放
//        //启动动画
//        imageView.startAnimation(scaleAnimation);
        /**
         * @param fromAlpha 开始的透明度，取值是0.0f~1.0f，0.0f表示完全透明， 1.0f表示和原来一样
         * @param toAlpha 结束的透明度，同上
         */
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.4f);
        //设置动画持续时长
        alphaAnimation.setDuration(3000);
        //设置动画结束之后的状态是否是动画的最终状态，true，表示是保持动画结束时的最终状态
        alphaAnimation.setFillAfter(true);
        //设置动画结束之后的状态是否是动画开始时的状态，true，表示是保持动画开始时的状态
        alphaAnimation.setFillBefore(true);
        //设置动画的重复模式：反转REVERSE和重新开始RESTART
        alphaAnimation.setRepeatMode(AlphaAnimation.REVERSE);
        //设置动画播放次数
        alphaAnimation.setRepeatCount(AlphaAnimation.INFINITE);
        //开始动画
        imageView.startAnimation(alphaAnimation);
//        //清除动画
//        imageView.clearAnimation();
//        //同样cancel()也能取消掉动画
//        alphaAnimation.cancel();

    }


    /**
     * 设置imageview 复杂动画
     * @param imageView
     */
    public void setImageViewComplexAnim(ImageView imageView){

        //设置复杂的操作步骤，点击按钮complex后，会运行四种动画效果叠加
        AnimationSet sets = new AnimationSet(true);
//        //定义渐变动画
//        AlphaAnimation _animation1 = new AlphaAnimation(1f, 0.4f);
//        _animation1.setDuration(3000);
//        _animation1.setRepeatMode(Animation.REVERSE );//结束后重新播放
//        _animation1.setRepeatCount(Animation.INFINITE );//一直播放
        //定义旋转动画，在物体的中心位置
        RotateAnimation rotateAnimation1 = new RotateAnimation(-45, 45, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation1.setRepeatMode(Animation.REVERSE );//结束后重新播放
        rotateAnimation1.setRepeatCount(Animation.INFINITE );//一直播放
        rotateAnimation1.setDuration(3000);
        //定义缩放动画，从中心坐标开始，缩放1.5倍大小
        ScaleAnimation scaleAnimation1 = new ScaleAnimation(0.9f, 1.1f, 0.9f, 1.1f, Animation.RELATIVE_TO_SELF, 0.2f, Animation.RELATIVE_TO_SELF, 0.2f);
        scaleAnimation1.setRepeatMode(Animation.REVERSE );//结束后重新播放
        scaleAnimation1.setRepeatCount(Animation.INFINITE );//一直播放
        scaleAnimation1.setDuration(3000);
        //定义移动动画，都从自身坐标开始，移动2个位置
        TranslateAnimation translateAnimation1 = new TranslateAnimation(imageView.getWidth(), imageView.getWidth()+5, imageView.getHeight(), imageView.getHeight()+5);
        translateAnimation1.setRepeatMode(Animation.REVERSE );//结束后重新播放
        translateAnimation1.setRepeatCount(Animation.INFINITE );//一直播放
      //  TranslateAnimation translateAnimation1 = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 2, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 2);
        translateAnimation1.setDuration(3000);
        //启动动画
     //   sets.addAnimation(_animation1);
        sets.addAnimation(rotateAnimation1);
        sets.addAnimation(scaleAnimation1);
        sets.addAnimation(translateAnimation1);

        imageView.startAnimation(sets);
    }




    /**
     * 将drawable对象进行指定大小的缩放
     * @param drawable
     * @param w
     * @param h
     * @return
     */
    public Drawable zoomDrawable(Drawable drawable, int w, int h) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap oldbmp = drawableToBitmap(drawable); // drawable 转换成 bitmap
        Matrix matrix = new Matrix(); // 创建操作图片用的 Matrix 对象
        float scaleWidth = ((float) w / width); // 计算缩放比例
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight); // 设置缩放比例
        Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true); // 建立新的 bitmap ，其内容是对原 bitmap 的缩放后的图
        return new BitmapDrawable(newbmp); // 把 bitmap 转换成 drawable 并返回
    }

    /**
     * 将drawable 转换成 bitmap
     * @param drawable
     * @return
     */
    public Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth(); // 取 drawable 的长宽
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; // 取 drawable 的颜色格式
        Bitmap bitmap = Bitmap.createBitmap(width, height, config); // 建立对应
        // bitmap
        Canvas canvas = new Canvas(bitmap); // 建立对应 bitmap 的画布
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas); // 把 drawable 内容画到画布中
        return bitmap;
    }




}
